#include <QSettings>
#include <QtDebug>

#include "tmthreadmanager.h"

#include "ClientThread.h"
//
CTMThreadManager::CTMThreadManager( QObject *pParent ) 
	: QObject(pParent)
{
	// create initial number of threads:
	QSettings settings;
	
	int nInitialNumThreads = settings.value("Threads/InitialThreadCount").toInt();
	qWarning() << "Initial thread count =" << nInitialNumThreads;
	createThreads(nInitialNumThreads);

}
//

void CTMThreadManager::newConnection(int nSocketDescriptor)
{
	// take a thread in the idle state, and pass it the socket descriptor.
	
	// idle thread pool should never be empty:
	if (m_liIdleThreads.isEmpty())
	{
		// create a few more threads anyway.
		QSettings settings;
		
		int nThreadGrowCount = settings.value("Threads/ThreadGrowCount").toInt();
		if (nThreadGrowCount <= 0)
			nThreadGrowCount = 1;
		createThreads(nThreadGrowCount);
	}
	
	CClientThread *pThread = m_liIdleThreads.takeFirst();
	if (pThread)
	{
		pThread->setSocketDescriptor(nSocketDescriptor);
	}
}

void CTMThreadManager::createThreads(int nCount)
{
	qWarning() << "Creating" << nCount << "threads";
	for (int i = 0; i < nCount; i++)
	{
		CClientThread *pThread = new CClientThread;
		connect(pThread, SIGNAL(newState(CClientThread::ClientThreadState)), this, SLOT(threadStateChanged(CClientThread::ClientThreadState)));
		pThread->start();
		
		m_liThreads.append(pThread);
		m_liIdleThreads.append(pThread);
	}
}

void CTMThreadManager::threadStateChanged(CClientThread::ClientThreadState nState)
{
	// only care about state changes to idle:
	if (nState == CClientThread::IdleState)
	{
		QObject *thread = sender();
	
		for (int i = 0 ; i < m_liThreads.count(); i++)
		{
			if (m_liThreads.at(i) == thread)
			{
				CClientThread *pIdleThread = m_liThreads.takeAt(i);
				m_liIdleThreads.append(pIdleThread);
				
				qWarning("Thread moved to idle state - moving thread to re-usable pool");
			}
		}
		
	}
}
